package com.bosssoft.trainee.nontax.config.security.service;
/*
用户认证处理类
@author shencanting
@date 2022/06/172118
**/

import com.bosssoft.trainee.nontax.entity.po.PermissionPO;
import com.bosssoft.trainee.nontax.entity.po.UserPO;
import com.bosssoft.trainee.nontax.service.PermissionService;
import com.bosssoft.trainee.nontax.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class CustomerUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用根据用户名查询用户信息的方法
        UserPO userPO = userService.findUserByUserName(username);
        //如果对象为空，则认证失败
        if (userPO == null) {
            throw new UsernameNotFoundException("用户名或密码错误!");
        }
        //查询用户的拥有的权限列表
        List<PermissionPO> permissionPOList =permissionService.findPermissionListByUserId(userPO.getId());
        //获取权限编码
        List<String> collect = permissionPOList.stream().filter(Objects::nonNull)
                .map(PermissionPO::getCode).filter(Objects::nonNull).collect(Collectors.toList());
        //转为数组
        String[] strings = collect.toArray(new String[collect.size()]);
        // 权限列表
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        userPO.setAuthorities(authorityList);
        userPO.setPermissionPOList(permissionPOList);
        return userPO;
    }
}
